#coding=utf-8
'''
Created on 2013-9-13

@author: Ben

请求模型

'''

from ..util import TimeUtil
from SocketService import gameSocketService

class RequestModel:
    '''
    classdocs
    '''
    
    #请求是否已发送
    req_sended = False
    #响应是否已收到
    resp_received = False
    #请求超时倒计时初始值
    req_timeout_init = 3
    #请求超时倒计时
    req_timeout = req_timeout_init
    #检查是否发送请求
    check = None
    #收到数据后回调
    callback = None
    #定时发送请求倒计时初始值
    interval_req_init = 0
    #定时发送请求倒计时偏移值
    interval_req_offset = 0
    #定时发送请求倒计时
    interval_req = interval_req_init
    #请求接口
    command = None
    #请求参数
    params = ''
    
    def __init__(self, check, callback, interval, offset):
        '''
        Constructor
        '''
        self.check = check
        self.callback = callback
        self.setCommand()
        self.interval_req_init = interval
        self.interval_req_offset = offset

    '''
    运行
    @return: 是否已处理
    '''
    def run(self):
        self.interval_req -= 1
        #请求已发送
        if self.req_sended:
            #响应已收到
            if self.resp_received:
                self.req_sended = False
                self.resp_received = False
                if self.callback != None:
                    self.callback()
            #响应未收到
            elif self.req_timeout > 0:
                self.req_timeout -= 1
            #响应超时
            else:
                self.req_sended = False
                self.resp_received = False
        #检查是否满足发送条件
        elif self.intervalCheck() or (self.check != None and self.check()):
            #发送请求
            self.onSend();
            self.send()
        else:
            return False
        return True
    
    '''
    定时发送请求检查
    '''
    def intervalCheck(self):
        if self.interval_req_init <= 0:
            return False
        elif self.interval_req <= 0:
            self.interval_req = TimeUtil.getRandomCount(self.interval_req_init, self.interval_req_offset)
            return True
        else:
            return False
    
    '''
    发送请求
    '''
    def send(self):
        self.req_timeout = self.req_timeout_init
        self.req_sended = True
        self.resp_received = False
        gameSocketService.send(self.command, self.params, self.receive)
        
    '''
    接受响应
    '''
    def receive(self, data):
        self.resp_received = True
        self.onReceive(data)
    
    '''
    设置请求接口
    '''
    def setCommand(self):
        pass
        
    '''
    发送请求前设置参数
    '''
    def onSend(self):
        pass
        
    '''
    收到响应后处理
    '''
    def onReceive(self, data):
        pass